package com.kwm;

import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

public class demo3 {
    private static final String TEACHER_OUTPUT_FILE = "teacher_math_problems.txt";
    private static final String STUDENT_OUTPUT_FILE = "student_math_problems.txt";
    private static final String STUDENT_ANSWERS_FILE = "student_answers.txt";
    private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        System.out.println("=== 数学题目生成系统（加减法） ===");

        // 选择用户类型
        UserType userType = selectUserType();

        // 获取题目数量
        int problemCount = getProblemCount();

        // 根据用户类型生成不同的题目
        List<MathProblem> problems = generateProblems(problemCount, userType);
        System.out.println("成功生成 " + problems.size() + " 道加减法数学题！");

        // 根据用户类型显示内容
        if (userType == UserType.STUDENT) {
            // 学生模式：先显示题目，然后询问是否完成
            displayStudentProblems(problems);
            boolean isFinished = askIfFinished();

            if (isFinished) {
                // 如果完成，显示答案并保存
                displayStudentAnswers(problems);
                saveStudentAnswers(problems);
            } else {
                // 如果未完成，只保存题目
                saveToFile(problems, userType, false);
            }
        } else {
            // 老师模式：直接显示题目和答案并保存
            displayProblems(problems, userType);
            saveToFile(problems, userType, true);
        }

        System.out.println("\n程序执行完毕！");
    }

    // 用户类型枚举
    enum UserType {
        STUDENT("学生"),
        TEACHER("老师");

        private final String displayName;

        UserType(String displayName) {
            this.displayName = displayName;
        }

        public String getDisplayName() {
            return displayName;
        }
    }

    // 数学题目类
    static class MathProblem {
        String expression;
        int answer;

        MathProblem(String expression, int answer) {
            this.expression = expression;
            this.answer = answer;
        }

        String getProblem() {
            return expression + " = ";
        }

        // 重写equals和hashCode确保题目唯一性
        @Override
        public boolean equals(Object obj) {
            if (this == obj) return true;
            if (obj == null || getClass() != obj.getClass()) return false;
            MathProblem that = (MathProblem) obj;
            return expression.equals(that.expression);
        }

        @Override
        public int hashCode() {
            return expression.hashCode();
        }
    }

    // 获取题目数量
    private static int getProblemCount() {
        System.out.print("\n请输入题目数量: ");

        while (true) {
            try {
                int count = Integer.parseInt(scanner.nextLine().trim());
                if (count <= 0) {
                    System.out.print("题目数量必须大于0，请重新输入: ");
                } else if (count > 1000) {
                    System.out.print("题目数量不能超过1000，请重新输入: ");
                } else {
                    return count;
                }
            } catch (NumberFormatException e) {
                System.out.print("请输入有效的数字: ");
            }
        }
    }

    // 生成题目
    private static List<MathProblem> generateProblems(int count, UserType userType) {
        List<MathProblem> problems = new ArrayList<>();
        Set<String> usedExpressions = new HashSet<>();
        Random random = new Random();

        // 老师和学生都使用随机种子，但使用不同种子确保题目不同
        if (userType == UserType.TEACHER) {
            // 老师题目使用当前时间作为种子
            random.setSeed(System.currentTimeMillis());
        } else {
            // 学生题目使用不同的种子
            random.setSeed(System.currentTimeMillis() + 1000);
        }

        // 只使用加法和减法
        String[] operators = {"+", "-"};

        while (problems.size() < count) {
            String operator = operators[random.nextInt(operators.length)];
            MathProblem problem = null;

            switch (operator) {
                case "+":
                    problem = generateAddition(random);
                    break;
                case "-":
                    problem = generateSubtraction(random);
                    break;
            }

            // 检查是否重复
            if (problem != null && !usedExpressions.contains(problem.expression)) {
                problems.add(problem);
                usedExpressions.add(problem.expression);
            }
        }

        return problems;
    }

    // 生成加法题目
    private static MathProblem generateAddition(Random random) {
        int a = random.nextInt(100) + 1;
        int b = random.nextInt(100) + 1;
        return new MathProblem(a + " + " + b, a + b);
    }

    // 生成减法题目
    private static MathProblem generateSubtraction(Random random) {
        int a = random.nextInt(100) + 1;
        int b = random.nextInt(100) + 1;
        // 确保结果不为负数
        if (a < b) {
            int temp = a;
            a = b;
            b = temp;
        }
        return new MathProblem(a + " - " + b, a - b);
    }

    // 选择用户类型
    private static UserType selectUserType() {
        System.out.println("\n请选择用户类型:");
        System.out.println("1. 学生 - 生成随机练习题");
        System.out.println("2. 老师 - 出题并保存题目");
        System.out.print("请输入选择 (1 或 2): ");

        while (true) {
            String input = scanner.nextLine().trim();
            if (input.equals("1")) {
                return UserType.STUDENT;
            } else if (input.equals("2")) {
                return UserType.TEACHER;
            } else {
                System.out.print("输入无效，请重新输入 (1 或 2): ");
            }
        }
    }

    // 显示学生题目（不含答案）
    private static void displayStudentProblems(List<MathProblem> problems) {
        System.out.println("\n" + "=".repeat(80));
        System.out.println("学生视图 - 加减法练习题 (" + problems.size() + "道题)");
        System.out.println("请解答以下题目:\n");

        int columns = 6;
        for (int i = 0; i < problems.size(); i++) {
            // 格式化输出，确保每列对齐
            String problem = String.format("%2d. %-15s", i + 1, problems.get(i).getProblem());
            System.out.print(problem);

            // 每6个题目换行
            if ((i + 1) % columns == 0) {
                System.out.println();
            }
        }
        // 如果最后一行不满，换行
        if (problems.size() % columns != 0) {
            System.out.println();
        }

        System.out.println("=".repeat(80));
    }

    // 显示学生答案
    private static void displayStudentAnswers(List<MathProblem> problems) {
        System.out.println("\n" + "=".repeat(80));
        System.out.println("参考答案:");

        int columns = 6;
        for (int i = 0; i < problems.size(); i++) {
            // 格式化答案，确保每列对齐
            String answer = String.format("%2d. %-13d", i + 1, problems.get(i).answer);
            System.out.print(answer);

            // 每6个答案换行
            if ((i + 1) % columns == 0) {
                System.out.println();
            }
        }
        // 如果最后一行不满，换行
        if (problems.size() % columns != 0) {
            System.out.println();
        }

        System.out.println("=".repeat(80));
    }

    // 显示老师题目和答案
    private static void displayProblems(List<MathProblem> problems, UserType userType) {
        System.out.println("\n" + "=".repeat(80));
        System.out.println("老师视图 - 加减法练习题及参考答案 (" + problems.size() + "道题)");
        System.out.println("题目和答案如下:\n");

        System.out.println("题目:");
        int columns = 6;
        for (int i = 0; i < problems.size(); i++) {
            // 格式化输出，确保每列对齐
            String problem = String.format("%2d. %-15s", i + 1, problems.get(i).getProblem());
            System.out.print(problem);

            // 每6个题目换行
            if ((i + 1) % columns == 0) {
                System.out.println();
            }
        }
        // 如果最后一行不满，换行
        if (problems.size() % columns != 0) {
            System.out.println();
        }

        System.out.println("\n参考答案:");
        for (int i = 0; i < problems.size(); i++) {
            // 格式化答案，确保每列对齐
            String answer = String.format("%2d. %-13d", i + 1, problems.get(i).answer);
            System.out.print(answer);

            // 每6个答案换行
            if ((i + 1) % columns == 0) {
                System.out.println();
            }
        }
        // 如果最后一行不满，换行
        if (problems.size() % columns != 0) {
            System.out.println();
        }

        System.out.println("=".repeat(80));
    }

    // 询问学生是否完成
    private static boolean askIfFinished() {
        System.out.print("\n题目已完成？(y/n): ");

        while (true) {
            String input = scanner.nextLine().trim().toLowerCase();
            if (input.equals("y") || input.equals("yes")) {
                return true;
            } else if (input.equals("n") || input.equals("no")) {
                return false;
            } else {
                System.out.print("请输入 y 或 n: ");
            }
        }
    }

    // 保存到文件
    private static void saveToFile(List<MathProblem> problems, UserType userType, boolean includeAnswers) {
        String filename;

        if (userType == UserType.TEACHER) {
            filename = TEACHER_OUTPUT_FILE;
        } else {
            filename = STUDENT_OUTPUT_FILE;
        }

        try (FileWriter writer = new FileWriter(filename)) {
            // 获取当前时间
            String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

            // 写入文件头
            if (includeAnswers) {
                writer.write("加减法练习题及参考答案\n");
                writer.write("生成时间: " + timeStamp + "\n");
            } else {
                writer.write("加减法练习题\n");
                writer.write("生成时间: " + timeStamp + "\n");
            }
            writer.write("题目数量: " + problems.size() + "\n");
            writer.write("=".repeat(50) + "\n\n");

            // 写入题目
            writer.write("题目:\n");
            int columns = 6;
            for (int i = 0; i < problems.size(); i++) {
                String problem = String.format("%2d. %-15s", i + 1, problems.get(i).getProblem());
                writer.write(problem);

                if ((i + 1) % columns == 0) {
                    writer.write("\n");
                }
            }

            // 如果最后一行不满，换行
            if (problems.size() % columns != 0) {
                writer.write("\n");
            }

            // 如果包含答案，写入答案
            if (includeAnswers) {
                writer.write("\n参考答案:\n");
                for (int i = 0; i < problems.size(); i++) {
                    String answer = String.format("%2d. %-13d", i + 1, problems.get(i).answer);
                    writer.write(answer);

                    if ((i + 1) % columns == 0) {
                        writer.write("\n");
                    }
                }

                // 如果最后一行不满，换行
                if (problems.size() % columns != 0) {
                    writer.write("\n");
                }
            }

            // 写入文件尾
            writer.write("\n" + "=".repeat(50) + "\n");
            writer.write("题目生成完毕\n");

            System.out.println("\n题目已保存到文件: " + filename);

        } catch (IOException e) {
            System.out.println("保存文件时出错: " + e.getMessage());
        }
    }

    // 保存学生答案到单独文件
    private static void saveStudentAnswers(List<MathProblem> problems) {
        try (FileWriter writer = new FileWriter(STUDENT_ANSWERS_FILE)) {
            // 获取当前时间
            String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

            // 写入文件头
            writer.write("学生练习题及参考答案\n");
            writer.write("生成时间: " + timeStamp + "\n");
            writer.write("题目数量: " + problems.size() + "\n");
            writer.write("=".repeat(50) + "\n\n");

            // 写入题目
            writer.write("题目:\n");
            int columns = 6;
            for (int i = 0; i < problems.size(); i++) {
                String problem = String.format("%2d. %-15s", i + 1, problems.get(i).getProblem());
                writer.write(problem);

                if ((i + 1) % columns == 0) {
                    writer.write("\n");
                }
            }

            // 如果最后一行不满，换行
            if (problems.size() % columns != 0) {
                writer.write("\n");
            }

            // 写入答案
            writer.write("\n参考答案:\n");
            for (int i = 0; i < problems.size(); i++) {
                String answer = String.format("%2d. %-13d", i + 1, problems.get(i).answer);
                writer.write(answer);

                if ((i + 1) % columns == 0) {
                    writer.write("\n");
                }
            }

            // 如果最后一行不满，换行
            if (problems.size() % columns != 0) {
                writer.write("\n");
            }

            // 写入文件尾
            writer.write("\n" + "=".repeat(50) + "\n");
            writer.write("答题完成\n");

            System.out.println("答案已保存到文件: " + STUDENT_ANSWERS_FILE);

        } catch (IOException e) {
            System.out.println("保存答案文件时出错: " + e.getMessage());
        }
    }
}